package com.zhouyu;

import com.zhouyu.service.UserService;
import com.zhouyu.service.UserServiceInterface;
//import org.springframework.cglib.proxy.*;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Test {

	public static void main(String[] args) {

//		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
//
//		UserService target = (UserService) applicationContext.getBean("userService");
		UserService target = new UserService();


		// cglib代理
		/*Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(UserService.class);
		enhancer.setCallbacks(new Callback[]{new MethodInterceptor(){

			@Override
			public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
				System.out.println("before...");
				Object result = methodProxy.invoke(target, objects);
				System.out.println("after...");
				return result;
			}

		}, NoOp.INSTANCE});

		// return返回的值對應上面設置的Callbacks的下表，也就是此處指定了代理的方法
		enhancer.setCallbackFilter(new CallbackFilter() {
			@Override
			public int accept(Method method) {
				if(method.getName().equals("test")){
					return 0;
				}
				return 1;
			}
		});

		UserService userService = (UserService) enhancer.create();
		userService.test();
		userService.test1();*/

		// jdk動態代理
//		UserServiceInterface userServiceInterface = (UserServiceInterface) Proxy.newProxyInstance(Test.class.getClassLoader(), new Class[]{UserServiceInterface.class}, new InvocationHandler() {
//			@Override
//			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//				System.out.println("before ...");
//				method.invoke(target, args);
//				System.out.println("after...");
//				return null;
//			}
//		});
//
//		userServiceInterface.test();

		// ProxyFactory
//		ProxyFactory proxyFactory = new ProxyFactory();
//		proxyFactory.setTarget(target);
////		proxyFactory.setInterfaces(UserServiceInterface.class); 加了這個會使用jdk的動態代理
//		proxyFactory.addAdvice(new MethodBeforeAdvice() {
//			@Override
//			public void before(Method method, Object[] args, Object target) throws Throwable {
//				System.out.println("before");
//			}
//		});
//		proxyFactory.addAdvice(new AfterReturningAdvice(){
//
//			@Override
//			public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
//				System.out.println("after");
//			}
//		});
//		UserService userService = (UserService) proxyFactory.getProxy();
//		userService.test();
	}
}
